package org.zjx.net.interceptor;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;
import org.zjx.log.LogLevel;
import org.zjx.log.Logger;

import java.io.IOException;

/**
 * 请求拦截器
 * @author llw
 */
public class RequestInterceptor implements Interceptor {
    private final Logger logger;  // 日志记录器

    public RequestInterceptor() {
        this.logger = Logger.getLogger();
    }

    /**
     * 拦截
     */
    @NotNull
    @Override
    public Response intercept(Chain chain) throws IOException {
        // 获取原始请求
        Request originalRequest = chain.request();

        // 在请求中添加请求头
        Request.Builder builder = originalRequest.newBuilder();
        builder.addHeader("Content-Type", "application/json");


        // 获取详细的请求信息
        String url = originalRequest.url().toString();
        String method = originalRequest.method();
        String headers = originalRequest.headers().toString();

        // 记录请求日志（你也可以在这里手动打印请求信息）
        logger.log("RequestInterceptor", LogLevel.INFO, "Http Request Log: ");
        logger.log("RequestInterceptor", LogLevel.INFO, "URL: " + url);
        logger.log("RequestInterceptor", LogLevel.INFO, "Method: " + method);
        logger.log("RequestInterceptor", LogLevel.INFO, "Headers: " + headers);

        // 创建新的请求
        Request newRequest = builder.build();

        // 返回处理后的响应
        return chain.proceed(newRequest);
    }
}
